package com.xiaoyu.tool.service.user;

import com.xiaoyu.tool.entity.User.User;
import com.xiaoyu.tool.repository.user.UserRepository;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpQrcodeService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Administrator on 2017/8/21.
 */
@Service
@Slf4j
public class UserService {


    @Autowired
    protected HttpServletRequest request;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private UserIntegralService userIntegralService;

    public synchronized User createAndUpdateUser(WxMpUser wxMpUser) {
        User user = userRepository.findByOpenId(wxMpUser.getOpenId());
        if (StringUtils.isEmpty(user)){
            user = new User();
        }
        user.setOpenId(wxMpUser.getOpenId());
        if (!StringUtils.isEmpty(wxMpUser.getSubscribe())){
            user.setIsFirstLogin(!wxMpUser.getSubscribe());
            user.setIsSubscribe(wxMpUser.getSubscribe());
        }
        user.setAvatar(wxMpUser.getHeadImgUrl());
        user.setNickName(wxMpUser.getNickname());
        createdQrCode(user);
        user = userRepository.save(user);
        userIntegralService.createUserIntegral(user);
        return user;
    }

    private void createdQrCode(User user) {
        if (StringUtils.isEmpty(user.getQrCodeUrl())) {
            String qrCodeUrl = null;
            try {
                qrCodeUrl = getQrCode(user.getId());
                user.setQrCodeUrl(qrCodeUrl);
            } catch (WxErrorException e) {
                log.error("生成用户永久二维码失败:{}", e.getMessage());
            }
        }
    }


    public synchronized void updateOrCreateUser(String openId) {
        User user = userRepository.findByOpenId(openId);
        if (StringUtils.isEmpty(user)){
            user = new User();
            user.setOpenId(openId);
            user.setIsFirstLogin(true);
        }else{
            user.setIsFirstLogin(false);
        }
        //获取用户信息-更新
        WxMpUser wxMpUser = null;
        try {
            wxMpUser = wxMpService.getUserService().userInfo(openId);
            user.setIsSubscribe(wxMpUser.getSubscribe());
            user.setAvatar(wxMpUser.getHeadImgUrl());
            user.setNickName(wxMpUser.getNickname());
        } catch (WxErrorException e) {
            log.error("通过openid获取用户信息失败：{}",e.getMessage());
        }
        createdQrCode(user);
        user = userRepository.save(user);
        userIntegralService.createUserIntegral(user);
    }

    private String getQrCode(Long userId) throws WxErrorException {
        WxMpQrcodeService qrcodeService = wxMpService.getQrcodeService();
        WxMpQrCodeTicket wxMpQrCodeTicket = qrcodeService.qrCodeCreateLastTicket(String.valueOf(userId));
        return qrcodeService.qrCodePictureUrl(wxMpQrCodeTicket.getTicket());
    }

    public User findByOpenId(String openId) {
        return userRepository.findByOpenId(openId);
    }

    public Long countTotalUsers() {
        return userRepository.count();
    }

    public List<User> findAll() {
        return userRepository.findAll();
    }

    public void addFansCount(Long userId, Integer fansCount) {
        User user = userRepository.findById(userId).orElse(null);
        if (StringUtils.isEmpty(fansCount) || StringUtils.isEmpty(user)){
            return;
        }
        user.setFansCount(fansCount);
        userRepository.save(user);
    }

    public void recusalAgent(Long userId) {
        User user = userRepository.findById(userId).orElse(null);
        if (!StringUtils.isEmpty(user)){
            user.setIsAgent(!user.getIsAgent());
            userRepository.save(user);
        }
    }
}
